-- meet_slime
-- created by panyl
-- 冈布奥事件：遇见冈布奥

-- 购买商场物品
EventMgr.register("meet_slime", event.START_DUNGEON, function(para)
    local unrealId = UnrealDungeonM.getUnrealId();
    if not unrealId then
        return;
    end

    local arr = SlimeEventM.getIdsByRule("meet_slime");
    for index = 1, #arr do
        SlimeEventM.triggerEvent(arr[index], {["unrealId"] = unrealId, });
    end
end);

return {
    checkEvent = function(eventId, para)
        local unrealId = para.unrealId;
        if not unrealId then
            return false;
        end

        local cond = SlimeEventM.query(eventId, "condition");
        if cond ~= unrealId then
            return false;
        end

        local dbase = SlimeEventM.query(eventId, "dbase");

        -- 如果是冈布奥
        if dbase["slime"] and ME.user.pets[dbase["slime"]] then
            return false;
        end
        -- 如果是碎片
        if dbase["slime_scrap"] and not ME.user.pets[dbase["slime_scrap"]] then
            return false;
        end

        -- 概率遇见
        local ratio = dbase["meet_ratio"] or 0;
        local rand = DungeonM.getRandSeed("meet_slime_event") % 100;

        if rand >= ratio then
            return false;
        end

        return true;
    end,

    triggerEvent = function(eventId, para)
        local dbase = SlimeEventM.query(eventId, "dbase");
        local bonus = SlimeEventM.calcEventBonus(eventId, para);
        local element = dbase["element"];
        local targetType = dbase["target_type"];
        local list = {};

        for pos = 1, GRID_SIZE do
            local grid = DungeonM.getGridByPos(pos);
            if grid.type == targetType then
                table.insert(list, pos);
            end
        end

        -- 找到目标
        if #list > 0 then
            local rand = DungeonM.getRandSeed("meet_slime_event") % #list;
            local class = DungeonM.queryElement(element, "class");

            local pos = list[rand + 1];

            local grid = DungeonM.transformGrid(class, pos, GRID_STATE_OPEN, {["element"] = element, ["bonus"] = bonus, });
            if grid then
                grid.bonus = bonus;
            end
        end

        return true;
    end,
};
